<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑订单</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .container {
            width: 80%;
            margin: 50px auto;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }

        .btn {
            display: inline-block;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            text-align: center;
            text-decoration: none;
            outline: none;
            border: none;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #45a049;
        }

        .btn-danger {
            background-color: #f44336;
            color: white;
        }

        .btn-danger:hover {
            background-color: #da190b;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>编辑订单</h2>
    <form id="editOrderForm">
        <div class="form-group">
            <label for="orderID">订单ID:</label>
            <input type="text" id="orderID" name="orderID" readonly>
        </div>
        <div class="form-group">
            <label for="userID">用户ID:</label>
            <input type="text" id="userID" name="userID" readonly>
        </div>
        <div class="form-group">
            <label>状态:</label>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="status" id="statusPending" value="Pending" checked>
                <label class="form-check-label" for="statusPending">未支付</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="status" id="statusPaid" value="Paid">
                <label class="form-check-label" for="statusPaid">已支付</label>
            </div>
        </div>
        <div class="form-group" id="alipayOrderIDGroup">
            <label for="alipayOrderID">支付宝支付订单号:</label>
            <input type="text" id="alipayOrderID" name="alipayOrderID">
        </div>
        <div class="form-group">
            <label for="totalAmount">总金额:</label>
            <input type="number" id="totalAmount" name="totalAmount" readonly>
        </div>
        <div class="form-group">
            <button type="button" onclick="updateOrder()">更新订单</button>
            <button type="button" onclick="window.history.back()">取消</button>
        </div>
    </form>
    <h3>订单详情</h3>
    <table class="table">
        <thead>
        <tr>
            <th>产品ID</th>
            <th>产品图片</th>
            <th>数量</th>
            <th>单价</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="orderDetailsTable">
        <!-- 订单详情将通过JavaScript动态填充 -->
        </tbody>
    </table>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const orderId = getParameterByName('id');
        if (orderId) {
            fetchOrderDetails(orderId);
        }
    });

    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
        var results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    function fetchOrderDetails(orderId) {
        fetch(`/api/orders/${orderId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(order => {
                document.getElementById('orderID').value = order.orderID;
                document.getElementById('userID').value = order.userID;
                if (order.status === 'Paid') {
                    document.getElementById('statusPaid').checked = true;
                    document.getElementById('alipayOrderID').value = order.alipayNo; // 自动填充支付宝订单号
                } else {
                    document.getElementById('statusPending').checked = true;
                }
                document.getElementById('totalAmount').value = order.totalAmount;
                loadOrderDetailsTable(order.orderID);
            })
            .catch(error => {
                console.error('Error fetching order details:', error);
                alert('获取订单详情失败: ' + error.message);
            });
    }

    function loadOrderDetailsTable(orderId) {
        fetch(`/api/orders/${orderId}/details`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(details => {
                const tableBody = document.getElementById('orderDetailsTable');
                tableBody.innerHTML = details.map(detail => `
                    <tr>
                        <td>${detail.product.productID}</td>
                        <td><img src="${detail.product.imageURL}" style="width:100px;height:100px;"></td>
                        <td><input type="number" id="quantity-${detail.orderDetailID}" value="${detail.quantity}"></td>
                        <td><input type="number" id="unitPrice-${detail.orderDetailID}" value="${detail.unitPrice}"></td>
                        <td>
                            <button class="btn btn-primary" onclick="updateOrderDetail(${detail.orderDetailID})">更新</button>
                        </td>
                    </tr>
                `).join('');
            })
            .catch(error => {
                console.error('Error fetching order details:', error);
                alert('获取订单详情失败: ' + error.message);
            });
    }

    function updateOrderDetail(detailId) {
        // 获取表单中的值
        const quantity = document.getElementById(`quantity-${detailId}`).value;
        const unitPrice = document.getElementById(`unitPrice-${detailId}`).value;

        // 构建要发送的更新数据对象，确保与后端期望的结构相匹配
        const updatedDetail = {
            id: detailId, // 包含订单详情的ID
            quantity: parseInt(quantity, 10), // 确保数量是整数
            unitPrice: parseFloat(unitPrice), // 确保单价是浮点数
            // 如果OrderDetail对象还需要其他属性，确保在这里添加
        };

        // 发送 PUT 请求到后端 API
        fetch(`/api/orderdetails/${detailId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(updatedDetail),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Success:', data);
                alert('订单详情更新成功');
                // 重新加载订单详情表以反映更改
                loadOrderDetailsTable(document.getElementById('orderID').value);
            })
            .catch(error => {
                console.error('Error:', error);
                alert('订单详情更新失败: ' + error.message);
            });
    }

    function updateOrder() {
        const orderId = document.getElementById('orderID').value;
        const status = document.querySelector('input[name="status"]:checked').value;
        const alipayOrderID = document.getElementById('alipayOrderID').value;

        if (status === 'Paid' && !alipayOrderID) {
            alert('如果状态为已支付，必须填写支付宝支付订单号');
            return;
        }

        fetch(`/api/orders/${orderId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ status, alipayNo: alipayOrderID }),
        })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                alert('订单更新成功');
                window.history.back();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('订单更新失败: ' + error.message);
            });
    }
</script>
</body>
</html>